import { createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

export const billStore = createSlice({
  name: 'bill',
  initialState: {
    billList: [],
  },
  reducers: {
    updateBillList(state, action) {
      const list = action.payload;
      return {
        ...state,
        billList: list.map((item) => ({
          ...item,
        })),
      };
    },
    addBill(state, action) {
      return {
        ...state,
        billList: [action.payload, ...state.billList],
      };
    },
  },
});

export const { updateBillList, addBill } = billStore.actions;

export const getBillData = () => {
  return async (dispatch) => {
    const { data } = await axios.get('http://localhost:3004/ka');
    dispatch(updateBillList(data));
  };
};

/* 
  callback: 回调 -- > 接口成功时再去调用
*/
export const addBillList = (data, callback) => {
  return async (dispatch) => {
    try {
      const res = await axios.post('http://localhost:3004/ka', data);
      dispatch(addBill(res.data));
      callback && callback();
    } catch (error) {}
  };
};

// import { useDispatch } from 'react-redux';

// const dispatch = useDispatch();

// function update(){
//     console.log('update')

//     function setState(){
//        // state
//     }
// }

// function useDispatch() {

//   function dispatch(customDispatch){

//     const promise = new Promise((resolve)=> {

//       customDispatch(update).then(()=> {
//         resolve()
//       })
//     })

//     return promise

//   }

//   return dispatch

// }

// const dispatch = useDispatch()

// dispatch(addBillList({}))
